package com.ddstation.crm.login.controller;

import com.ddstation.crm.accountManage.Entity.AccountManageEntity;
import com.ddstation.crm.accountManage.service.AccountManageService;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionDoctorEntity;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionDoctorMapper;
import com.ddstation.crm.institution.model.UserAccountModel;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crm.login.service.LoginAccountService;
import com.ddstation.crm.login.util.ValidateUtil;
import com.ddstation.crm.login.util.WnSessionUtil;
import com.ddstation.crud.entity.DtInvsManageInstitutionSupervisorEntity;
import com.ddstation.crud.mapper.DtInvsManageInstitutionSupervisorMapper;
import com.ddstation.security.util.WnBizMsgCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 《健康管理平台》 登录用户管理
 * @author zhangdifeng
 * @date 2017年8月22日
 */
@Controller
public class LoginUserManageController {

	/**
	 * 新建账户
	 * @param session
	 * @param name
	 * @param phone
	 * @param authType
	 * @param loginUser
	 * @param loginPassword
	 * @param model
	 * @return
	 */
	@RequestMapping(value="wncrm_loginuser_manage.do/add")
	public @ResponseBody Map<String, Object> addEvent(
			HttpSession session,
			@RequestParam(required=false) String name,
			@RequestParam(required=false) String cityYbDoctorServiceName,
			@RequestParam(required=false) String phone,
			@RequestParam(required=false, defaultValue="1") Integer authType,
			@RequestParam(required=false) Integer accountType,
			@RequestParam(required=false) String loginUser,
			@RequestParam(required=false) String loginPassword,
			@RequestParam(required=false) Integer orgId,
			@RequestParam(required=false) Integer isManager,
			@RequestParam(required=false) String cityYbDoctorServiceNb,
//			@RequestParam(required=false) String provinceYbDoctorServiceNb,
			@RequestParam(required=false) String clinicDptCd,
			@RequestParam(required=false) String cityDptCd,
			@RequestParam(required=false) String provinceDptCd,
			@RequestParam(required=false) String doctorCredentialsCode,//医生资格证编号
			@RequestParam(required=false, defaultValue="1") Integer role,
			Model model) {
		
		String institutionId = WnSessionUtil.getInstitutionId(session);

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errorcode", -1);
		// 从session获取基础数据
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			ret.put("errormsg", "无法获取到权限，请尝试重新登录");
		} else if (loginData.getIsManager() != 1) {
			ret.put("errormsg", "权限不足，无法执行操作");
		} else if (authType != 1 && authType != 2 && authType !=4) {
			ret.put("errormsg", "权限不正确【not in 1，2，4】");
		} else if (StringUtils.isBlank(loginUser)) {
			ret.put("errormsg", "未输入登录账户");
		} else if (StringUtils.isBlank(loginPassword)) {
			ret.put("errormsg", "未输入登录密码");
		} else {
			int userLength = loginUser.length();
			if (userLength < 6 || userLength > 16) {
				ret.put("errormsg", "请输入6-16位用户名");
				return ret;
			} else if (!ValidateUtil.chkLoginUserPw(loginUser)) {
				ret.put("errormsg", "用户名需要由数字/字母/下划线组成");
				return ret;
			}
			
			int pwLength = loginPassword.length();
			if (pwLength < 6 || pwLength > 16) {
				ret.put("errormsg", "请输入6-16位密码");
				return ret;
			} else if (!ValidateUtil.chkLoginUserPw(loginPassword)) {
				ret.put("errormsg", "密码需要由数字/字母/下划线组成");
				return ret;
			}
			
			DtInvsManageInstitutionSupervisorEntity supervisorEntity = dtInvsManageInstitutionSupervisorMapper.selectByUserName("invs_" + loginUser);
			if (supervisorEntity != null) {
				ret.put("errormsg", "登录账户已经存在");
			} else {
				int doctorId = loginAccountService.add(
						institutionId, name, phone,null, loginUser, loginPassword, orgId, isManager, null);
				ret.put("uuid", WnBizMsgCrypt.encrypt(String.valueOf(doctorId)));
				List<AccountManageEntity> freeAccounts = accountManageService.getFreeAccount(institutionId);
				ret.put("freeAccountCnt", freeAccounts == null ? 0 : freeAccounts.size());
				ret.put("errorcode", 0);
			}
		}
		return ret;
	}
	
	/**
	 * 修改账户
	 * @param session
	 * @param doctorUUID
	 * @param name
	 * @param phone
	 * @param authType
	 * @param accountType
	 * @param loginUser
	 * @param orgId
	 * @param isManager
	 * @param model
	 * @return
	 */
	@RequestMapping(value="wncrm_loginuser_manage.do/replace")
	public @ResponseBody Map<String, Object> replaceEvent(
			HttpSession session,
			@RequestParam String doctorUUID,
			@RequestParam(required=false) String loginPassword,
			@RequestParam(required=false) String name,
			@RequestParam(required=false) String cityYbDoctorServiceName,
			@RequestParam(required=false) String phone,
			@RequestParam(required=false) Integer authType,
			@RequestParam(required=false) Integer accountType,
			@RequestParam(required=false) String loginUser,
			@RequestParam(required=false) Integer orgId,
			@RequestParam(required=false, defaultValue="0") Integer isManager,
			@RequestParam(required=false) String cityYbDoctorServiceNb,
//			@RequestParam(required=false) String provinceYbDoctorServiceNb,
			@RequestParam(required=false) String clinicDptCd,
			@RequestParam(required=false) String cityDptCd,
			@RequestParam(required=false) String provinceDptCd,
			@RequestParam(required=false) String doctorCredentialsCode,//医生资格证编号
			@RequestParam(required=false, defaultValue="1") Integer role,
			Model model) {
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errorcode", -1);
		
//		DdDoctorEntity doctorInfo = ddDoctorMapper.selectDoctorInfo(Integer.parseInt(WnBizMsgCrypt.decrypt(doctorUUID)));
//		if (doctorInfo.getPhone() == null || !doctorInfo.getPhone().equals(phone)) {
//			int cnt = ddDoctorMapper.selectDoctorCntByPhone(phone);
//			if (cnt > 0) {
//				ret.put("errormsg", "电话号码已存在");
//			}
//		} else {
//			phone = null;
//		}
		
		String institutionId = WnSessionUtil.getInstitutionId(session);
		String doctorId = WnBizMsgCrypt.decrypt(doctorUUID);
		
		int userLength = loginUser.length();
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			ret.put("errormsg", "无法获取到权限，请尝试重新登录");
			return ret;
		} else if (loginData.getIsManager() != 1) {
			ret.put("errormsg", "权限不足，无法执行操作");
			return ret;
		} else if (userLength < 4 || userLength > 16) {
			ret.put("errormsg", "请输入4-16位用户名");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginUser)) {
			ret.put("errormsg", "用户名需要由数字/字母/下划线组成");
			return ret;
		}else if(loginPassword != null && (loginPassword.length() < 6 || loginPassword.length() > 16)){
			ret.put("errormsg", "请输入4-16位密码");
			return ret;
		}else if(loginPassword != null && (!ValidateUtil.chkLoginUserPw(loginPassword))){
			ret.put("errormsg", "密码需要由数字/字母/下划线组成");
			return ret;
		}

		DtInvsManageInstitutionSupervisorEntity supervisorEntity = dtInvsManageInstitutionSupervisorMapper.selectByUserName("invs_" + loginUser);
		// 账号id是否唯一
		boolean accountUnion = false;
		if (supervisorEntity == null) {
			accountUnion = true;
		} else {
			if (institutionId.equals(supervisorEntity.getInstitutionId()) &&
				doctorId.equals(supervisorEntity.getSupervisorId().toString())) { // self
				accountUnion = true;
			}
		}
		if (!accountUnion) {
			ret.put("errormsg", "用户名已经存在");
		} else {
//			if (accountType == 110) { // 主账户 配超级权限
//				authType = 4;
//			} else {
//				authType = 1;
//			}
//			if (loginAccountService.replace(
//					institutionId, doctorId, name, phone, authType, accountType, loginUser, orgId, isManager, clinicDptCd,
//					cityYbDoctorServiceNb, cityYbDoctorServiceNb, cityDptCd, provinceDptCd, doctorCredentialsCode,
//					role,cityYbDoctorServiceName, loginPassword) == 1) {
//				ret.put("errorcode", 0);
//			}
		}
		
		return ret;
	}
	
	/**
	 * 删除账户
	 * @param session
	 * @param doctorUUID
	 * @param model
	 * @return
	 */
	@RequestMapping(value="wncrm_loginuser_manage.do/remove")
	public @ResponseBody Map<String, Object> removeEvent(
			HttpSession session,
			@RequestParam String doctorUUID,
			Model model) {
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errorcode", -1);
		String doctorId = WnBizMsgCrypt.decrypt(doctorUUID);
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			ret.put("errormsg", "无法获取到权限，请尝试重新登录");
		} else if (loginData.getIsManager() != 1) {
			ret.put("errormsg", "权限不足，无法执行操作");
		} else if (doctorId.equals(WnSessionUtil.getDoctorId(session))) { // 不能删除自己
			ret.put("errorcode", -2);
		} else {
			String institutionId = WnSessionUtil.getInstitutionId(session);
			if (loginAccountService.remove(institutionId, doctorId) == 1) {
				List<AccountManageEntity> freeAccounts = accountManageService.getFreeAccount(institutionId);
				ret.put("freeAccountCnt", freeAccounts == null ? 0 : freeAccounts.size());
				ret.put("errorcode", 0);
			}
		}
		
		return ret;
	}
	
	/**
	 * 查看所有用户
	 */
	@RequestMapping(value="wncrm_loginuser_manage.do/getAccount")
	public @ResponseBody Map<String, Object> getAccountEvent(
			HttpSession session) {
		
		Map<String, Object> retMap = new HashMap<String, Object>();
		
		List<UserAccountModel> accountList = loginAccountService.getAllAccount(WnSessionUtil.getInstitutionId(session));
		
		retMap.put("accountList", accountList);
		retMap.put("errorcode", 0);
		
		return retMap;
	}
	
	/**
	 * 取得可增加帐号版本
	 */
	@RequestMapping(value="wncrm_loginuser_manage.do/getAccountType")
	public @ResponseBody Map<String, Object> getAccountTypeEvent(
			HttpSession session) {
		
		Map<String, Object> retMap = new HashMap<String, Object>();
		
		List<Map<String, Object>> accountList = loginAccountService.getRemainderAccountType(WnSessionUtil.getInstitutionId(session));
		
		retMap.put("accountList", accountList);
		retMap.put("errorcode", 0);
		
		return retMap;
	}
	
	@Inject private LoginAccountService loginAccountService = null;
//	@Inject private DdDoctorMapper ddDoctorMapper = null;
//	@Inject private DdDoctorServiceItf doctorService = null;
	@Inject private AccountManageService accountManageService = null;
	@Inject private DtHealthManageInstitutionDoctorMapper dtHealthManageInstitutionDoctorMapper = null;
	@Inject private DtInvsManageInstitutionSupervisorMapper dtInvsManageInstitutionSupervisorMapper = null;

}
